<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>节流</title>
</head>

<body>
  <button id="btnthrottle">点击节流</button>
  <script>

    // 1、时间戳写法，第一次会立即执行
    function throttle(fn, interval) {
      let last = 0;
      return function () {
        let now = Date.now();
        if (now - last >= interval) {
          last = now;
          fn.apply(this, arguments);
        }
      }
    }

    // 2、定时器写法 第一次不立即执行，但最后一次也会延迟执行
    function throttle1(fn, interval) {
      let timer = null;
      return function () {
        console.log(this);
        let context = this;
        let arg = arguments;
        if (!timer) {
          console.log(timer);
          timer = setTimeout(function () {
            fn.apply(context, arguments);
            timer = null;
          }, interval);
          console.log(timer);
        }
      }
    }

    function throttle(fn, delay) {
      let timer;
      return function () {
        if (!timer) {
          timer = setTimeout(() => {
            fn();
            timer = null;
          }, delay)
        }
      }
    }

    // 3、结合版本
    function throttle(fn, interval) {
      let timer = null;
      let startTime = Date.now();
      return function () {
        let curTime = Date.now();
        let remainning = interval - (curTime - startTime);
        let context = this;
        let arg = arguments;
        if (remainning <= 0) {
          fn.apply(context, arguments);
          startTime = Date.now();
        } else {
          timer = setTimeout(fn, remainning);
        }
      }
    }

    function throttle(fn, interval) {
      let canRun = true;
      return function () {
        console.log("1");
        if (!canRun) {
          console.log("2");
          return;
        }
        let context = this;
        canRun = false;
        setTimeout(function () {
          console.log("3");
          fn.apply(context, arguments);
          canRun = true;
        }, 10000);
      }
    }
    function handle() {
      console.log("执行了");
    }

    const throttleHandle = throttle1(handle, 10000);
    const btn = document.getElementById('btnthrottle');
    btn.addEventListener("click", throttleHandle);
    // const btn = document.getElementById('btnthrottle');
    // btn.addEventListener("click", throttleHandle);


  </script>
</body>

</html>